package com.csmk.springboot_simple.aop;


import com.csmk.springboot_simple.exception.ServiceException;
import com.csmk.springboot_simple.util.Null;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class PageAop {
    @Pointcut("@annotation(com.csmk.springboot_simple.annotation.StartPage)")
    public void pointCut() {}

    @Around(value = "pointCut()")
    public Page<?> doAroundAdvice(ProceedingJoinPoint proceedingJoinPoint){
        try {
            Integer pageNum = getPageParam("pageNum");
            Integer pageSize = getPageParam("pageSize");
            // 拿不到分页参数就不分页了
            if (!Null.hasEmpty(pageNum,pageSize)){
                PageHelper.startPage(pageNum,pageSize);
            }
            Object res = proceedingJoinPoint.proceed();
            if(res instanceof Page){
                return (Page<?>) res;
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        throw new ServiceException("分页异常");
    }

    /**
     * requestContextHolder中获取分页参数
     * @param name
     * @return
     */
    public Integer getPageParam(String name){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null){
            return null;
        }
        HttpServletRequest request = requestAttributes.getRequest();
        return Integer.parseInt(request.getParameter(name));
    }
}
